package com.mxp.influx.client.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;

/**
 * Sqlite数据库初始化
 * @author maoxp
 * @date 2024-12-30 15:44
 */
@Slf4j
@Configuration
public class SqliteDatabaseInitConfig {

    /**
     * 数据源
     */
    @Resource
    private DataSource dataSource;

    /**
     * 执行数据库初始化
     * @return
     */
    @Bean
    public CommandLineRunner sqliteDatabaseInit() {
        return args -> {
            try (Connection connection = dataSource.getConnection()) {
                DatabaseMetaData metaData = connection.getMetaData();
                ResultSet clientConnection = metaData.getTables(null, null, "client_connection", new String[]{"TABLE"});
                if (clientConnection.next()) {
                    log.info("数据已存在，无需初始化...");
                } else {
                    ScriptUtils.executeSqlScript(connection, new ClassPathResource("db/init.sql"));
                    log.info("初始化SQL执行完成...");
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        };
    }
}
